//
//  TTOrderDetailViewController.m
//  TaoTuo
//
//  Created by admin on 2019/10/9.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTOrderDetailViewController.h"
#import "TTOrderDetailModel.h"
#import "TTOrderDetailHeaderView.h"
#import "TTCellLabelMiddleModel.h"
#import "TTCellLabelModel.h"
#import "TTCellLabelRightButtonModel.h"
#import "TTCommonViewCell.h"
#import "TTOrderDetailShopViewCell.h"
#import "TTBankCardModel.h"
#import "TTBankCardViewCell.h"
#import <UIImageView+WebCache.h>
#import "LLInputAlertView.h"
#import <UIView+TYAlertView.h>
#import "TTDiamondViewController.h"
#import "TTPayRecordCellModel.h"
#import "TTPayRecordCell.h"
#import "TTPayOrderDetailViewController.h"
#import "TTQualityCheckModel.h"
#import "TTShopCartSubDetailModel.h"
#import "TTInlayRuleModel.h"

#import "TTPayHintViewCell.h"
#import "TTDianpuImageViewCell.h"
#import "TTDianpuImageCellModel.h"

#import "TTDianpuUploadImageViewController.h"

#import "TTChangeHandSizePopView.h"
#import "TTQualityCheckPopListView.h"

#define cellTypeKey @"cellTypeKey"
#define titleKey @"titleKey"
#define datasKey @"datasKey"

static NSString *shopCellID = @"shop_cell_id";
static NSString *infoCellID = @"info_cell_id";
static NSString *cardCellID = @"card_cell_id";
static NSString *payRecordCellID = @"pay_record_cell_id";
static NSString *payHintCellID = @"pay_hint_cell_id";
static NSString *payImageCellID = @"pay_image_cell_id";

typedef enum : NSUInteger {
    CellTypeWithShop,
    CellTypeWithInfo,
    CellTypeWithPayRecord,
    CellTypeWithCard,
    CellTypeWithPayCredentials,
} CellType;

@interface TTOrderDetailViewController ()<UITableViewDelegate, UITableViewDataSource, TTPayRecordCellDelegate, TTPayHintViewCellDelegate, TTDianpuImageViewCellDelegate>
{
    TTCellLabelRightButtonModel *remarkModel;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) TTOrderDetailHeaderView *headerView;

@property (nonatomic, strong) TTOrderDetailModel *detailModel;
@property (nonatomic, assign) CGFloat totalCellH;   // 商品cell高度

@property (nonatomic, copy) NSString *orderNo;  // 订单编号

///需要被镶嵌的model
@property (nonatomic, strong) TTShopCartSubDetailModel *needInlayModel;
@property (nonatomic, strong) NSMutableArray *inlayRuleArray;

@property (nonatomic, strong) NSMutableArray *qcListArray;
@property (nonatomic, strong) TTQualityCheckPopListView *qcView;

@end

@implementation TTOrderDetailViewController

- (instancetype)initWithOrderNo:(NSString *)orderNo
{
    self = [super init];
    if (self) {
        self.orderNo = orderNo;
    }
    return self;
}

//防止多次推出页面发出多次通知
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNotifyEvent];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单详情";
    [self tableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseZSFinishedNotify:) name:@"orderPageModifyQualityCheckNotify_key" object:nil];
    
    [self getNetworkData];
    
}

- (void)addNotifyEvent
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exchangeLuoshiNotify:) name:@"exchangeLuoshiNotify_key" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworkData) name:@"refreshDatasNotify_key" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworkData) name:@"handSizeChangeSuccessNotify_key" object:nil];
    //镶嵌选择完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertFinishedNotify:) name:@"chooseFinishedQualityCheckNotify_key" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needInlayLuoshiOrKongtuoNotify:) name:@"needInlayLuoshiOrKongtuo_key" object:nil];
}

- (void)needInlayLuoshiOrKongtuoNotify:(NSNotification *)notify
{
    self.needInlayModel = (TTShopCartSubDetailModel *)notify.object;
}



// 计算镶嵌费
- (NSString *)calculateInlayMoneyWithStoneSize:(NSString *)insertSize
{
    NSInteger money = 0;
    CGFloat size = insertSize.floatValue;// * 100;
    for (TTInlayRuleModel *model in self.inlayRuleArray) {
        if (size >= model.InsertSizeMin && size < model.InsertSizeMax) {
            money = model.InlayValuationPriceType == 0 ? model.InlayPrice : (NSInteger)(size * model.UnitPrice);
            break;
        }
    }
    return [NSString stringWithFormat:@"%ld", money];
}

//镶嵌选择完成
- (void)insertFinishedNotify:(NSNotification *)notify
{
    TTOrderShopModel *shopModel = self.detailModel.Detail.firstObject;
    TTQualityCheckModel *checkModel = (TTQualityCheckModel *)notify.object;
    //镶嵌费
    NSString *inlayMoneyStr = @"0";
    CGFloat inlayMoney = 0;
    if (self.needInlayModel.GoodsType == 1) {
        inlayMoney = self.needInlayModel.DiaSize.floatValue * 100;
        inlayMoneyStr = [self calculateInlayMoneyWithStoneSize:[NSString stringWithFormat:@"%.0f", inlayMoney]];
    } else {
        inlayMoneyStr = [self calculateInlayMoneyWithStoneSize:shopModel.DiaSize];
    }
    
    NSDictionary *dic = @{
        @"param.wholesalerName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"param.orderNo" : self.detailModel.OrderNo,
        @"param.goodsBarCode" : shopModel.GoodsBarCode,
        @"param.diaOrderNo" : self.needInlayModel.OrderNo,
        @"param.diaGoodsBarCode" : self.needInlayModel.GoodsBarCode,
        @"param.goodsInlayCertTypeCode" : @(checkModel.CertType),
        @"param.goodsInlayCertType" : checkModel.CertTypeName,
        @"param.inlayPrice" : inlayMoneyStr,
        @"param.certPrice" : checkModel.Price,
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:orderDetailInlayFinish_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [self getNetworkData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

///更换裸石
- (void)exchangeLuoshiNotify:(NSNotification *)notify
{
    TTOrderShopModel *model = (TTOrderShopModel *)notify.object;
    NSDictionary *dic = @{
        @"param.shape" : model.ShapeEn,
        @"param.diaSizeMin" : model.DiaSize,
        @"param.diaSizeMax" : model.DiaSize,
        @"param.cert" : model.Cert,
        @"param.color" : model.Color,
        @"param.clarity" : model.Clarity,
        @"param.cut" : model.Cut,
        @"param.polish" : model.Polish,
        @"param.sym" : model.Sym,
        @"param.flour" : model.Flour,
        @"param.milky" : model.Milky,
        @"param.browness" : model.Browness,
        @"param.isFromSouthAfrica" : model.SouthAfrica ? @"true" : @"false",
    };
    @weakify(self)
    TTDiamondViewController *diamondVC = [[TTDiamondViewController alloc] init];
    diamondVC.paramsDic = dic.mutableCopy;
    diamondVC.isExchangeLuoshi = YES;
    [diamondVC replaceLuoshiOrderNumber:model.OrderNo confirmReplaceBlock:^{
        @strongify(self)
        [self getNetworkData];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"replaceLuoshiSuccessNotify_key" object:nil];
    }];
    [self.navigationController pushViewController:diamondVC animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSArray *array = dic[datasKey];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    NSInteger type = [dic[cellTypeKey] intValue];
    if (type == CellTypeWithShop) {
        
        TTOrderDetailShopViewCell *cell = [tableView dequeueReusableCellWithIdentifier:shopCellID];
        [cell setDataArray:dic[datasKey][indexPath.row] orderType:self.detailModel.OrderType goodsCertType:self.detailModel.GoodsCertType detailModel:self.detailModel];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else if (type == CellTypeWithInfo) {
        
        TTCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCellID];
        cell.model = dic[datasKey][indexPath.row];
        return cell;
    } else if (type == CellTypeWithPayRecord) {
        id model = dic[datasKey][indexPath.row];
        if ([model isKindOfClass:[TTCellLabelModel class]]) {
            TTCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCellID];
            cell.model = model;
            return cell;
        } else {
            TTPayRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:payRecordCellID];
            cell.model = model;
            cell.delegate = self;
            return cell;
        }
    }
    else if (type == CellTypeWithCard) {
        TTBankCardViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cardCellID];
        cell.model = dic[datasKey][indexPath.row];
        return cell;
    } else if (type == CellTypeWithPayCredentials) {
        id model = dic[datasKey][indexPath.row];
        if ([model isKindOfClass:[TTCellLabelMiddleModel class]]) {
            TTCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCellID];
            cell.model = model;
            return cell;
        } else if ([model isKindOfClass:[TTDianpuImageCellModel class]]) {
            TTDianpuImageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:payImageCellID];
            cell.model = (TTDianpuImageCellModel *)model;
            cell.delegate = self;
            return cell;
        } else {
            TTPayHintViewCell *cell = [tableView dequeueReusableCellWithIdentifier:payHintCellID];
            cell.delegate = self;
            return cell;
        }
        
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        return cell;
    }
}

///选取图片上传，直接替换掉dic
- (void)chooseImagesUploadActionWithCell:(UITableViewCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    __block NSMutableDictionary *dic = [self.dataArray[indexPath.section] mutableCopy];
    //直接替换掉dic
    TTDianpuUploadImageViewController *uploadVC = [[TTDianpuUploadImageViewController alloc] init];
    uploadVC.canEdit = NO;
    [uploadVC setIsUploadPayImage:YES orderNo:self.detailModel.OrderNo canModify:self.detailModel.IsAllowUploadPaymentVoucher];
    uploadVC.imagesArray = self.detailModel.PaymentVouchers;
    //图片上传完成的回调
    @weakify(self)
    uploadVC.uploadFinishedBlock = ^(NSArray * _Nonnull imageUrlArray) {
        @strongify(self)
        self.detailModel.PaymentVouchers = imageUrlArray;
        if (imageUrlArray.count > 0) {
            NSArray *arr = @[[TTDianpuImageCellModel setModelWithTitle:@"支付凭证" fontSize:15 imageUrlArray:imageUrlArray]];
            [dic setObject:arr forKey:datasKey];
        } else {
            NSArray *arr = @[[TTCellLabelMiddleModel setModelWithTitle:@"支付凭证" midText:@"如果您是线下转账汇款，请上传凭证。" midTextColor:UIColorHex(FF5555) midFontSize:10], [NSObject new]];
            [dic setObject:arr forKey:datasKey];
        }
        [self.dataArray replaceObjectAtIndex:indexPath.section withObject:dic];
        [self.tableView reloadSection:indexPath.section withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:uploadVC animated:YES];
}

#pragma mark - TTPayHintViewCellDelegate
- (void)gotoUploadPayImages:(TTPayHintViewCell *)payHintCell
{
    [self chooseImagesUploadActionWithCell:payHintCell];
}

#pragma mark - TTDianpuImageViewCellDelegate
- (void)clickImgCell:(TTDianpuImageViewCell *)imgCell model:(TTDianpuImageCellModel *)model
{
    [self chooseImagesUploadActionWithCell:imgCell];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    NSInteger type = [dic[cellTypeKey] intValue];
    if (type == CellTypeWithShop) {
        return self.totalCellH + 8;
    } else if (type == CellTypeWithInfo || type == CellTypeWithPayRecord) {
        if ([[dic[datasKey] firstObject] isKindOfClass:[TTCellLabelMiddleModel class]]) {
            id model = dic[datasKey][indexPath.row];
            if (model == remarkModel) {
                return remarkModel.height;
            }
            return UITableViewAutomaticDimension;
        } else {
            return 44;
        }
    } else if (type == CellTypeWithPayCredentials) {
        id model = dic[datasKey][indexPath.row];
        if ([model isKindOfClass:[TTCellLabelMiddleModel class]]) {
            return 44;
        } else if ([model isKindOfClass:[TTDianpuImageCellModel class]]) {
            return 130;
        }
        return 60;
    } else {
        return 130;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSString *title = dic[titleKey];
    return title.length > 0 ? 50 : 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSString *title = dic[titleKey];
    if (title.length > 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 46)];
        view.backgroundColor = [UIColor whiteColor];
        [LLLineUtilies addLineInView:view startPoint:CGPointZero endPoint:CGPointMake(view.width, 0) lineColor:kSeparatorColor lineWidth:10];
        UILabel *label = [UILabel labelWithTitle:title color:UIColorHex(282828) font:[UIFont fontWithName:@"Source Han Sans CN" size: 14]];
        label.frame = CGRectMake(10, 10, view.width - 20, view.height - 10);
        [view addSubview:label];
        UIColor *bottomLineColor = section == 0 ? [UIColor whiteColor] : kSeparatorColor;
        [LLLineUtilies addLineInView:view startPoint:CGPointMake(10, view.bottom) endPoint:CGPointMake(view.width - 10, view.bottom) lineColor:bottomLineColor];
        
        if (section == 0 && self.detailModel.OrderState.intValue <= 55) {
            UIEdgeInsets insets = UIEdgeInsetsMake(3, 8, 3, 8);
            UIButton *gscBtn = [UIButton createButtonWithTitle:@"改手寸" titleColor:kMainColor titleFontSize:10 borderColor:kMainColor cornerRadius:10 * kScale contentEdgeInsets:insets target:self action:@selector(gscBtnClick)];
            
            UIButton *gzsBtn = [UIButton createButtonWithTitle:@"改证书" titleColor:kMainColor titleFontSize:10 borderColor:kMainColor cornerRadius:10 * kScale contentEdgeInsets:insets target:self action:@selector(gzsBtnClick)];
            UIButton *cancleBtn = [UIButton createButtonWithTitle:@"取消镶嵌" titleColor:kMainColor titleFontSize:10 borderColor:kMainColor cornerRadius:10 * kScale contentEdgeInsets:insets target:self action:@selector(cancleBtnClick)];
            
            UIStackView *topStackView = [[UIStackView alloc] initWithFrame:CGRectMake(view.width - 175 * kScale, label.centerY - 15, 165 * kScale, 30)];
            topStackView.axis = UILayoutConstraintAxisHorizontal;
            topStackView.alignment = UIStackViewAlignmentCenter;
            topStackView.distribution = UIStackViewDistributionEqualCentering;
            topStackView.spacing = 5;
            if (self.detailModel.GoodsType == 1) {
                // 裸石
                if (self.detailModel.InlayRelateGoodsList.count > 0) {
                    // 已镶嵌
                    [topStackView addArrangedSubview:[UIView new]];
                    [topStackView addArrangedSubview:gzsBtn];
                    [topStackView addArrangedSubview:cancleBtn];
                    [view addSubview:topStackView];
                }
            } else {
                // 托
                TTOrderShopModel *osm = self.detailModel.Detail.firstObject;
                if (self.detailModel.InlayRelateGoodsList.count > 0) {
                    // 已镶嵌
                    if ([osm.CategoryName isEqualToString:@"女戒"] || [osm.CategoryName isEqualToString:@"男戒"] || [osm.CategoryName isEqualToString:@"对戒"]) {
                        [topStackView addArrangedSubview:gscBtn];
                    }
                    [topStackView addArrangedSubview:gzsBtn];
                    [topStackView addArrangedSubview:cancleBtn];
                } else {
                    // 未镶嵌
                    if ([osm.CategoryName isEqualToString:@"女戒"] || [osm.CategoryName isEqualToString:@"男戒"] || [osm.CategoryName isEqualToString:@"对戒"]) {
                        [topStackView addArrangedSubview:[UIView new]];
                        [topStackView addArrangedSubview:[UIView new]];
                        [topStackView addArrangedSubview:gscBtn];
                    }
                }
                [view addSubview:topStackView];
            }
            
        }
        
        return view;
    } else {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 10)];
        view.backgroundColor = kSeparatorColor;
        return view;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSInteger type = [dic[cellTypeKey] intValue];
    if (type == CellTypeWithCard) {
        return 10;
    }
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSInteger type = [dic[cellTypeKey] intValue];
    if (type == CellTypeWithCard) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 10)];
        return view;
    }
    return [UIView new];
}

///请求改手寸接口
- (void)gotoChangeHandSize:(int)handSize
{
    TTOrderShopModel *model = self.detailModel.Detail.firstObject;
    NSDictionary *dic = @{
        @"param.wholesalerName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"param.orderNo" : self.detailModel.OrderNo,
        @"param.goodsBarCode" : model.GoodsBarCode,
        @"param.updateHandSize" : @(handSize),
        @"param.orderUpdateHandSizePrice" : @(30)
    };
    
    [[LLNetworkManagerTool sharedManager] postUrlString:updateHandSize_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"handSizeChangeSuccessNotify_key" object:nil];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

///改手寸的弹窗
- (void)changeHandSizeAction
{
    if (self.detailModel.UpdateHandSize > 0) {
        return;
    }
    @weakify(self)
    TTChangeHandSizePopView *popView = [TTChangeHandSizePopView changeHandSizeViewWithCurrentHandSize:self.detailModel.HandSize selectBlock:^(int handSize) {
        @strongify(self)
        [self confirmChangeHandSize:handSize];
    }];
    [TYShowAlertView showAlertViewWithView:popView backgoundTapDismissEnable:YES];
}

///确定改手寸的弹窗
- (void)confirmChangeHandSize:(int)handSize
{
    NSString *str = [NSString stringWithFormat:@"确定要将%d#手寸改成%d#吗？", self.detailModel.HandSize, handSize];
    @weakify(self)
    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"改手寸" message:str cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" confirmBlock:^BOOL{
        @strongify(self)
        [self gotoChangeHandSize:handSize];
        return YES;
    }];
    
//    [alertView showInView:nil animationDuration:0];
    [alertView showInWindowWithBackgoundTapDismissEnable:YES];
}

// 改手寸
- (void)gscBtnClick
{
//    if (self.detailModel.UpdateHandSize > 0) {
//        return;
//    }
    @weakify(self)
    TTChangeHandSizePopView *popView = [TTChangeHandSizePopView changeHandSizeViewWithCurrentHandSize:self.detailModel.HandSize selectBlock:^(int handSize) {
        @strongify(self)
        [self confirmChangeHandSize:handSize];
    }];
    [TYShowAlertView showAlertViewWithView:popView backgoundTapDismissEnable:YES];

}

// 选择证书完成
- (void)chooseZSFinishedNotify:(NSNotification *)notify
{
    TTQualityCheckModel *qcModel = notify.object;
    //TODO:修改证书
    NSString *zuanNum = @"", *tuoNum = @"";
    if (self.detailModel.GoodsType == 1) {
        // 裸钻
        zuanNum = self.detailModel.OrderNo;
        TTOrderShopModel *osm = self.detailModel.InlayRelateGoodsList.firstObject;
        tuoNum = osm.OrderNo;
    } else {
        tuoNum = self.detailModel.OrderNo;
        TTOrderShopModel *osm = self.detailModel.InlayRelateGoodsList.firstObject;
        zuanNum = osm.OrderNo;
    }
    NSDictionary *dic = @{
        @"param.wholesalerName" : [TTLoginSingle sharedSingle].loginModel.SalesmanAccountName,
        @"param.orderNo" : tuoNum,
        @"param.diaOrderNo" : zuanNum,
        @"param.goodsInlayCertTypeCode" : @(qcModel.CertType),
        @"param.goodsInlayCertType" : qcModel.CertTypeName,
        @"param.certPrice" : qcModel.Price
    };
    
    [[LLNetworkManagerTool sharedManager] postUrlString:updateCert_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"handSizeChangeSuccessNotify_key" object:nil];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
    
}

//  改证书
- (void)gzsBtnClick
{
    if (self.qcListArray.count > 0) {

        [self setQualityCheckData];

        return;
    }
    // 请求质检证书列表
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getQualityCheck_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        [self.qcListArray removeAllObjects];
        for (NSDictionary *dic in responseObject) {
            TTQualityCheckModel *model = [TTQualityCheckModel modelWithJSON:dic];
            [self.qcListArray addObject:model];
        }
        
        [self setQualityCheckData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

// 取消镶嵌
- (void)cancleBtnClick
{
    NSDictionary *dic = @{
        @"param.wholesalerName" : [TTLoginSingle sharedSingle].loginModel.SalesmanAccountName,
        @"param.orderNo" : self.detailModel.OrderNo
    };
    [[LLNetworkManagerTool sharedManager] postUrlString:cancelInlay_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"handSizeChangeSuccessNotify_key" object:nil];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}


- (void)setQualityCheckData
{
    NSNumber *num;
    if (self.detailModel.GoodsType == 1) {
        TTOrderShopModel *sm = self.detailModel.Detail.firstObject;
        num = sm.DiaSize.numberValue;
    } else {
        TTOrderShopModel *sm = self.detailModel.InlayRelateGoodsList.firstObject;
        num = sm.DiaSize.numberValue;
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"DiaSizeMin <= %@ && DiaSizeMax > %@", num, num];
    NSArray *array = [self.qcListArray filteredArrayUsingPredicate:predicate];
    
    if (array.count == 0) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"没有符合的质检证书" duration:1 position:CSToastPositionCenter];
        return;
    }
    _qcView = [TTQualityCheckPopListView popListViewWithLastView:nil];
    _qcView.hiddenLeftBtn = YES;
    self.qcView.dataArray = array;
    [self.qcView showInView:nil animationDuration:0.5];
    
}


///点击支付按钮
- (void)payRecordViewCellToPay:(TTPayRecordCellModel *)model
{
    TTPayOrderDetailViewController *payVC = [[TTPayOrderDetailViewController alloc] initWithPayType:model.payType OrderNum:self.detailModel.OrderNo totalMoney:self.detailModel.OrderRealPayPrice];
    [self.navigationController pushViewController:payVC animated:YES];
}

- (void)getNetworkData
{
//    [MBProgressHUD showLoadingAnimationOnView:self.view];
    co_launch(^{
        // 1. 详情model
        TTOrderDetailModel *detailModel = await([self getOrderDetailData]);
        self.detailModel = detailModel;
        // 镶嵌费
        await([self getIgetInlayPriceRule]);
        //物流
        TTLookProgressModel *progressModel = await([self getShopProgress]);
        
        if (detailModel == nil) {
//            [MBProgressHUD dismissAnimationOnView:self.view];
            [self.tableView reloadData];
            return;
        }
        // 2. 银行卡列表
        NSArray *bankArray = await([self getBankCardList]);

//        [MBProgressHUD dismissAnimationOnView:self.view];
        // 计算高度
        self.totalCellH = 0;
        for (TTOrderShopModel *shopModel in detailModel.Detail) {
            [self calculateCellHeightWithShopModel:shopModel];
        }
        for (TTOrderShopModel *shopModel in detailModel.InlayRelateGoodsList) {
            [self calculateCellHeightWithShopModel:shopModel];
        }
        self.totalCellH += 40;
        if (detailModel.InlayRelateGoodsList.count > 0) {
            self.totalCellH += 30;
        }

        [self.headerView setModel:detailModel progressModel:progressModel];
        [self.headerView layoutIfNeeded];

        self.tableView.tableHeaderView = self.headerView;
        [self setupFooterView];
//
        [self setupDatasWithModel:detailModel bankList:bankArray];
        
        [self.tableView reloadData];
        
    });
}

// 获取详情数据
- (COPromise *)getOrderDetailData
{
    COPromise *promise = [COPromise promise];
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:orderDetail_api parameters:@{@"param.orderNo" : self.orderNo} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        TTOrderDetailModel *detailModel = [TTOrderDetailModel modelWithJSON:responseObject];
        
        [promise fulfill:detailModel];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [promise fulfill:nil];
        
    } showLoadingInView:nil];
    
    return promise;
}

///获取镶嵌费规则
- (COPromise *)getIgetInlayPriceRule
{
    COPromise *promise = [COPromise promise];
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:getInlayPriceRule parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [self.inlayRuleArray removeAllObjects];
        for (NSDictionary *dic in responseObject) {
            TTInlayRuleModel *model = [TTInlayRuleModel modelWithJSON:dic];
            [self.inlayRuleArray addObject:model];
        }
        [promise fulfill:self.inlayRuleArray];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        [promise fulfill:nil];
    } showLoadingInView:nil];
    
    return promise;
}

///物流进度
- (COPromise *)getShopProgress
{
    NSDictionary *dic = @{
        @"param.orderNo" : self.orderNo,
        @"param.pageIndex" : @1,
        @"param.pageSize" : @50
    };
    
    COPromise *promise = [COPromise promise];
    
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:lookOrderProgress_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr = responseObject;
        if (arr.count == 0) {
            [promise fulfill:nil];
        } else {
            NSDictionary *dic = arr.firstObject;
            TTLookProgressModel *model = [TTLookProgressModel modelWithJSON:dic];
            [promise fulfill:model];
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        [promise fulfill:nil];
    } showLoadingInView:self.view];
    
    return promise;
    
}



- (COPromise *)getBankCardList
{
    COPromise *promise = [COPromise promise];
    
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:bankCardList_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in responseObject) {
            TTBankCardModel *bankModel = [TTBankCardModel modelWithJSON:dic];
            [arr addObject:bankModel];
        }
        
        [promise fulfill:arr];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [promise fulfill:nil];
        
    } showLoadingInView:nil];
    
    return promise;
}

// 计算cell高度
- (void)calculateCellHeightWithShopModel:(TTOrderShopModel *)shopModel
{
    CGFloat cellImageH = 65 * kScale + 40;
    
    if (shopModel.GoodsType == 1) {
        shopModel.h = cellImageH + 10;
    } else {
        NSData *data = [shopModel.GoodsDescribe dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *describe = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *content = [describe componentsJoinedByString:@"\n"];
        CGFloat contentH = [content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 65 * kScale - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.height + 68 + 10;
        
        contentH = contentH < cellImageH ? cellImageH : contentH;
        
        shopModel.h = contentH;
        //定制的
        if (shopModel.GoodsType == 2) {
            shopModel.h = contentH + 15;
        }
    }
    
    self.totalCellH += shopModel.h;
}

/// 修改备注
- (void)updateRemark:(NSString *)remark
{
    NSString *content = remark.length > 0 ? remark : @" ";
    NSDictionary *dic = @{
        @"param.wholesalerName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"param.orderNo" : self.orderNo,
        @"param.orderRemark" : content
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:updateRemark_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [self.view makeToast:@"修改成功"];
        self->remarkModel.midText = content;
        
        self->remarkModel.height = [self getRemarkContentHeight:content];
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

// 修改备注
- (void)changeRemark
{
    @weakify(self)
    LLInputAlertView *inputView = [LLInputAlertView inputViewWithTitle:@"修改备注" content:remarkModel.midText maxTextCount:200 confirmBlock:^(NSString * _Nullable content) {
        @strongify(self)
        [self updateRemark:content];
    }];
    [inputView showInWindowWithBackgoundTapDismissEnable:YES];
}

- (CGFloat)getRemarkContentHeight:(NSString *)content
{
    CGFloat h = [content boundingRectWithSize:CGSizeMake(self.view.width - 110, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingUsesDeviceMetrics | NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil].size.height + 15;
    return h > 44 ? h : 44;
}

- (void)setupDatasWithModel:(TTOrderDetailModel *)model bankList:(NSArray *)bankArray
{
    NSArray *shopsArray = @[model.Detail];
    if (model.InlayRelateGoodsList.count > 0) {
        shopsArray = @[model.Detail, model.InlayRelateGoodsList];
    }
    
    remarkModel = [TTCellLabelRightButtonModel setModelWithTitle:@"备注:" midText:model.OrderRemark.length == 0 ? @" " : model.OrderRemark rightButtonTitle:@"修改" rightButtonTitleColor:kMainColor target:self selector:@selector(changeRemark)];
    remarkModel.height = [self getRemarkContentHeight:model.OrderRemark];

    //支付的
    NSMutableArray *payArray = [NSMutableArray array];
    [payArray addObject:[TTCellLabelModel setModelWithTitle:@"订单应付总金额" content:[NSString stringWithFormat:@"￥%@", model.OrderRealPayPrice] contentColor:UIColorHex(FF1F1F)]];
    for (TTPayRecorListModel *payModel in model.PayRecorList) {
        [payArray addObject:[TTPayRecordCellModel setPayModelWithPayType:payModel.PayType payTypeName:payModel.PayTypeName payDate:payModel.PayDate payMethod:payModel.PayMethod payMoney:payModel.PayMoney isGoToPay:payModel.isGoToPay stepState:payModel.StepState orderStatus:model.OrderState.intValue]];
    }
    if (payArray.count > 1) {
        TTPayRecordCellModel *firstModel = payArray[1];
        firstModel.hiddenTopLine = YES;
        TTPayRecordCellModel *lastModel = payArray.lastObject;
        lastModel.hiddenBottomLine = YES;
    }
    NSArray *infoArr = @[
            [TTCellLabelModel setModelWithTitle:@"优惠金额" content:[NSString stringWithFormat:@"￥%@", model.OrderDiscountPrice] contentColor:UIColorHex(FF1F1F)],
            [TTCellLabelModel setModelWithTitle:@"配送费用" content:@"￥0" contentColor:UIColorHex(FF1F1F)],
            [TTCellLabelModel setModelWithTitle:@"镶嵌服务费" content:[NSString stringWithFormat:@"￥%@", model.OrderInlayPrice] contentColor:UIColorHex(FF1F1F)],
            [TTCellLabelModel setModelWithTitle:@"证书费" content:[NSString stringWithFormat:@"￥%@", model.OrderCertPrice] contentColor:UIColorHex(FF1F1F)],
    ];
    NSMutableArray *infoArray = [NSMutableArray arrayWithArray:infoArr];
    if (model.OrderUpdateHandSizePrice.intValue > 0) {
        [infoArray addObject:[TTCellLabelModel setModelWithTitle:@"改手寸费" content:[NSString stringWithFormat:@"￥%@", model.OrderUpdateHandSizePrice] contentColor:UIColorHex(FF1F1F)]];
    }
    //支付图片上传
    NSDictionary *dic = @{};
    if (self.detailModel.OrderState.intValue != 80 && self.detailModel.OrderState.intValue != 81) {
        if (self.detailModel.PaymentVouchers.count > 0) {
            dic = @{
                cellTypeKey : @(CellTypeWithPayCredentials),
                datasKey : @[[TTDianpuImageCellModel setModelWithTitle:@"支付凭证" fontSize:15 imageUrlArray:self.detailModel.PaymentVouchers]]
            };
        } else {
            dic = @{
                cellTypeKey : @(CellTypeWithPayCredentials),
                datasKey : @[[TTCellLabelMiddleModel setModelWithTitle:@"支付凭证" midText:@"如果您是线下转账汇款，请上传凭证。" midTextColor:UIColorHex(FF5555) midFontSize:10], [NSObject new]]
            };
        }
        
    }
    
    
    NSArray *arr = @[
        @{
            cellTypeKey : @(CellTypeWithShop),
            titleKey : @"商品列表",
            datasKey : @[shopsArray]
        },
        @{
            cellTypeKey : @(CellTypeWithInfo),
            datasKey : infoArray
        },
        @{
            cellTypeKey : @(CellTypeWithPayRecord),
            datasKey : payArray
        },
        dic,
        @{
            cellTypeKey : @(CellTypeWithInfo),
            datasKey : @[
                    [TTCellLabelMiddleModel setModelWithTitle:@"订单号:" midText:model.OrderNo],
                    [TTCellLabelMiddleModel setModelWithTitle:@"下单时间:" midText:model.CreateTime],
                    remarkModel
            ]
        },
        @{
            cellTypeKey : @(CellTypeWithCard),
            titleKey : @"请您将货款汇至以下任意账户",
            datasKey : bankArray
        },
        @{
            cellTypeKey : @(999),
            titleKey : @"您的专属业务顾问",
            datasKey : @[]
        },
    ];

    self.dataArray = arr.mutableCopy;
    if (dic.count == 0) {
        [self.dataArray removeObject:dic];
    }
}

// 联系导购
- (void)contactBtnClick
{
    [[TTLoginSingle sharedSingle].loginModel.SalesmanMobile callPhone];
}

// 订单状态按钮
- (void)orderBtnClick:(UIButton *)sender
{
    NSString *title = sender.titleLabel.text;
    if ([title isEqualToString:@"取消订单"]) {
        
        NSDictionary *dic = @{
            @"param.orderNo" : self.detailModel.OrderNo,
            @"param.relationName" : [TTLoginSingle sharedSingle].loginModel.RealName
        };
        @weakify(self)
        [[LLNetworkManagerTool sharedManager] postUrlString:cancleOrder_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            @strongify(self)
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"setPageRefreshStatusNotify" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshPageCountNotify" object:nil];
            
            [self.navigationController popViewControllerAnimated:YES];
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
            
        } showLoadingInView:self.view];
        
    }
}

// footer
- (void)setupFooterView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 110)];
    
    UIImageView *headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 45, 45)];
    headImageView.contentMode = UIViewContentModeScaleAspectFit;
//    headImageView.image = [UIImage imageNamed:@"header_img"];
    headImageView.layer.cornerRadius = 22.5;
    headImageView.layer.masksToBounds = YES;
    [footerView addSubview:headImageView];
    NSString *headerUrlString = [[TTLoginSingle sharedSingle].loginModel.SalesmanPicture stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [headImageView sd_setImageWithURL:[NSURL URLWithString:headerUrlString] placeholderImage:[UIImage imageNamed:@"header_img"] options:SDWebImageRetryFailed];
    
    
    UILabel *nameLabel = [UILabel labelWithTitle:[TTLoginSingle sharedSingle].loginModel.SalesmanAccountName color:UIColorHex(666666) fontSize:14];
    UILabel *phoneLabel = [UILabel labelWithTitle:[TTLoginSingle sharedSingle].loginModel.SalesmanMobile color:UIColorHex(333333) fontSize:15];
    UIStackView *stView = [[UIStackView alloc] initWithFrame:CGRectMake(headImageView.right + 6, headImageView.top, footerView.width - headImageView.right - 16, headImageView.height)];
    stView.axis = UILayoutConstraintAxisVertical;
    stView.distribution = UIStackViewDistributionFillEqually;
    stView.alignment = UIStackViewAlignmentFill;
    [stView addArrangedSubview:nameLabel];
    [stView addArrangedSubview:phoneLabel];
    [footerView addSubview:stView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [[TTLoginSingle sharedSingle].loginModel.SalesmanMobile callPhone];
    }];
    [stView addGestureRecognizer:tap];
    
    [LLLineUtilies addLineInView:footerView startPoint:CGPointMake(0, headImageView.bottom + 10) endPoint:CGPointMake(footerView.width, headImageView.bottom + 10) lineColor:kSeparatorColor lineWidth:10];
    
    UIButton *contactBtn = [UIButton createButtonWithTitle:@"联系导购" titleColor:kMainColor titleFontSize:14 borderColor:kMainColor cornerRadius:12.5 contentEdgeInsets:UIEdgeInsetsMake(6, 9, 6, 9) target:self action:@selector(contactBtnClick)];
    [footerView addSubview:contactBtn];
    [contactBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(stView.mas_bottom).mas_offset(30);
        make.right.equalTo(footerView).mas_offset(-10);
        make.width.mas_equalTo(90);
        make.height.mas_equalTo(25);
    }];
    
    
    NSInteger orderState = self.detailModel.OrderState.integerValue;
    if (orderState == 10) {
        // 取消订单才有
        NSString *title = [TTOrderStatusUtilis getTitleByOrderStatus:orderState];
        UIButton *orderBtn = [UIButton createButtonWithTitle:title titleColor:UIColorHex(333333) titleFontSize:14 borderColor:UIColorHex(333333) cornerRadius:12.5 contentEdgeInsets:UIEdgeInsetsMake(6, 9, 6, 9) target:self action:@selector(orderBtnClick:)];
        [footerView addSubview:orderBtn];
        [orderBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(contactBtn);
            make.right.equalTo(contactBtn.mas_left).mas_offset(-15);
            make.width.height.equalTo(contactBtn);
        }];
    }
    
    self.tableView.tableFooterView = footerView;
    
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.emptyImageName = @"tao_nodata";
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 44;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _tableView.separatorColor = kSeparatorColor;
        [_tableView registerClass:[TTOrderDetailShopViewCell class] forCellReuseIdentifier:shopCellID];
        [_tableView registerClass:[TTCommonViewCell class] forCellReuseIdentifier:infoCellID];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTPayRecordCell class]) bundle:nil] forCellReuseIdentifier:payRecordCellID];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTBankCardViewCell class]) bundle:nil] forCellReuseIdentifier:cardCellID];
        [_tableView registerClass:[TTPayHintViewCell class] forCellReuseIdentifier:payHintCellID];
        [_tableView registerClass:[TTDianpuImageViewCell class] forCellReuseIdentifier:payImageCellID];
        
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (TTOrderDetailHeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [TTOrderDetailHeaderView orderDetailHeaderView];
    }
    return _headerView;
}

- (NSMutableArray *)inlayRuleArray
{
    if (!_inlayRuleArray) {
        _inlayRuleArray = [NSMutableArray array];
    }
    return _inlayRuleArray;
}

- (NSMutableArray *)qcListArray
{
    if (!_qcListArray) {
        _qcListArray = [NSMutableArray array];
    }
    return _qcListArray;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
